// miniprogram/pages/user/record-detail/record-detail.js
import {addBrowsingRecords} from "../../../service/User"
import {getUnlimitedCode} from "../../../service/Open"
import {getRecordDetail} from "../../../service/Record";
import {getTempFileURL} from "../../../service/File"
import {getStorageSync} from "../../../utils/Storage";
import {hiddenPhoneNumber} from "../../../utils/Util";
import Toast from "@vant/weapp/toast/toast";
import Notify from "@vant/weapp/notify/notify";
import PosterConfig from "../../../utils/PosterConfig";

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isOneself: false, //是否发布信息的人
        pageShow: false,  //是否展示页面
        isHasDetail: true, //是否有内容
        detail: {}, //详情内容
        share: {
            show: false,
            config: {}
        },
        messageShow: false,
        authorizeCheck: false, //是否开启授权检测
    },
    ___pageTitle: "", //页面标题
    ___headImage: "", //海报头图 //减少请求
    ___wxCodeImage: "", //微信小程序码  //减少请求


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this._options = options;
        this.getRecordDetail()
    },

    /*
    * 获取记录详情
    * */
    getRecordDetail: async function () {
        try {
            let detail = await getRecordDetail(this._options.id) || {};
            this.___pageTitle = detail.type === 'lost' ? "寻物启事" : "拾物认领";
            wx.setNavigationBarTitle({title: this.___pageTitle});
            let isOneself = getStorageSync("userInfo.openId") === detail.openId;
            detail.hiddenPhone = hiddenPhoneNumber(detail.phone);
            if (detail.verify !== 2) {
                detail.complete === 1 ? Notify({
                    type: "success",
                    message: detail.type === 'lost' ? "失物已找回" : "拾物已被认领",
                    duration: 0
                }) : null
                this.setData({ //注入数据
                    isOneself: isOneself,
                    detail: detail,
                    authorizeCheck: true
                })
                addBrowsingRecords({ //增加浏览记录
                    rid: detail._id,
                    sharerId: this._options.sharerId
                }).catch(function (e) {
                    console.error(e)
                })
            } else {  //审核不通过 只有自己 和 管理员可以看
                this.setData({
                    isOneself: isOneself,
                    detail: detail,
                    isHasDetail: getStorageSync("userInfo.isManager") || isOneself
                });
            }
        } catch (e) {
            this.setData({isHasDetail: false});
            console.error(e)
        } finally {
            this.setData({pageShow: true})
        }
    },

    /*
    * 图片点击预览
    * */
    bindImageClick: function (e) {
        wx.previewImage({
            current: e.currentTarget.dataset.src, // 当前显示图片的http链接
            urls: this.data.detail.images // 需要预览的图片http链接列表
        })
    },

    /*
    * 打电话
    * */
    bindCallNumber: function (e) {
        let phone = e.currentTarget.dataset.phone;
        wx.makePhoneCall({phoneNumber: phone})
    },

    /*
    * 点击按钮
    * */
    bindShareBtn: async function() {
        this.setData({"share.show": true});
    },

    //插入海报数据
    onSharePosterClickPyqBtn: async function (e) {
        try {
            Toast.loading({
                mask: true,
                duration: 0,
                message: "海报生成中...",
            });
            await this._sharePyqImageCreate();
        } catch (e) {
            Toast.clear();
            console.error(e)
        }
    },
    onSharePoster: function () {
        Toast.clear();
    },


    _sharePyqImageCreate: async function () { //分享朋友圈海报
        let detail = this.data.detail;
        let tempFilePath = this.___headImage || (detail.images.length > 0 ? await getTempFileURL([detail.images[0]]) : ""); //因为是云地址 需要兑换成临时路径
        let wxCodeImage = this.___wxCodeImage || await getUnlimitedCode(
            "/pages/user/record-detail/record-detail?id="
            + this._options.id
            + "&sharerId=" + getStorageSync("userInfo.openId")
        );
        this.___headImage = tempFilePath;
        this.___wxCodeImage = wxCodeImage;
        this.setData({
            "share.config": PosterConfig.sharePyqImage({
                type: detail.type,
                title: this.___pageTitle,
                name: detail.name,
                phone: detail.phone,
                intro: detail.intro,
                headImage: tempFilePath ? tempFilePath[0].tempFileURL : "",
                address: detail.region + detail.regionDetail,
                wxCodeImage: wxCodeImage.filePath
            })
        })
    },


    /*
    * 弹出留言框
    * */
    onAuthorizeBtn: function (e) {
        this.setData({messageShow: true})
    },

    //留言变动
    onMessage: function () {
        wx.createSelectorQuery().select("#box").boundingClientRect(function(rect){
            wx.pageScrollTo({
                scrollTop: rect.height,
            });
        }).exec()
    },


    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        let detail = this.data.detail;
        return {
            title: this.___pageTitle + (detail.intro ? "：" + detail.intro : ""),
            path: "/pages/user/record-detail/record-detail?id=" + detail._id + "&sharerId=" + getStorageSync("userInfo.openId"),
            imageUrl: detail.images[0] || ""
        }
    },

    /*
    * 开启分享朋友圈
    * */
    onShareTimeline: function () {
        let detail = this.data.detail;
        return {
            title: this.___pageTitle + (detail.intro ? "：" + detail.intro : ""),
            query: {
                id: detail._id,
                sharerId: getStorageSync("userInfo.openId")
            },
            imageUrl: detail.images[0] || ""
        }
    }
})